
let arr2 = [
  {
    id: 1,
    name: '部门A',
    parentId: 0,
    children: [
      {
        id: 3,
        name: '部门C',
        parentId: 1,
        children: [
          {
            id: 6,
            name: '部门F',
            parentId: 3,
          }
        ]
      },
      {
        id: 4,
        name: '部门D',
        parentId: 1,
        children: [
          {
            id: 8,
            name: '部门H',
            parentId: 4
          }
        ]
      },
    ]
  },
  {
    id: 2,
    name: '部门B',
    parentId: 0,
    children: [
      { id: 5, name: '部门E', parentId: 2 },
      { id: 7, name: '部门G', parentId: 2 },
    ]
  }
];

// 广度优先搜索  按层查找 针对同层的id是顺序的 用此方法
function wideTraversal(arr) {
  const queue = arr;
  const res = [];
  while (queue.length > 0) {
    let node = queue.shift();
    res.push({
      id: node.id,
      name: node.name,
      parentId: node.parentId
    })
    let children = node.children;
    if (children) {
      for (let i = 0; i < children.length; i++) {
        queue.push(children[i])
      }
    }
  }
  return res;
}

console.log(wideTraversal(arr2));

// 深度优先搜索  先序遍历  针对父子节点是顺序的
// function deepTraversal(arr) {
//   const res = [];
//   for (const item of arr) {
//     function dfs(node) {
//       res.push({
//         id: node.id,
//         name: node.name,
//         parentId: node.parentId
//       });
//       let children = node.children;
//       if (children) {
//         for (let i = 0; i < children.length; i++) {
//           // 递归子节点
//           dfs(children[i]);
//         }
//       }
//     }
//     dfs(item);
//   }
//   return res;
// }

// console.log(deepTraversal(arr2));
